//
//  LogInController.m
//  ios_51job
//
//  Created by kai ren on 28/09/2011.
//  Copyright 2011 none. All rights reserved.
//

#import "LogInController.h"


@implementation LogInController

@synthesize OAuthInfo, conToken, conAccessToken, delegate;

#pragma mark -
#pragma mark other

- (id)initWithDeleget:(NSObject<LogInControllerDelegate> *)object{
	if (self = [super init]) {
		self.delegate = object;
		self.conToken = nil;
		self.conAccessToken = nil;
		self.OAuthInfo = [[NSMutableDictionary alloc] initWithCapacity:0];
	}
	
	return self;
}

- (void)loadWeb{
	NSString *url = [NSString stringWithFormat:@"%@%@", verifyUrl, [OAuthInfo objectForKey:TOKEN_KEY]];
	NSURL *requestUrl = [NSURL URLWithString:url];
	NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
	[verifyWebView loadRequest:request];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	_data = [[NSMutableData alloc] initWithCapacity:0];
	
	verifyWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 416)];
	verifyWebView.delegate = self;
	
	UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
																			   target:self 
																			   action:@selector(Cancel)];
	
	NSMutableArray *barItems = [[NSMutableArray alloc] initWithCapacity:0];
	UINavigationItem *barItem = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(@"Login", nil)];
	
	barItem.leftBarButtonItem = btnCancel;
	[barItems addObject:barItem];
	bar.items = barItems;
	bar.tintColor = [UIColor orangeColor];
	
	[self.view addSubview:bar];
	[self.view addSubview:verifyWebView];
	
	[barItems release];
	[barItem release];
	[bar release];
	
	[self getTonkenKey];
}


- (void)Cancel{
	[delegate LogInCancel];
	[self dismissModalViewControllerAnimated:YES];
}

-(NSString*) valueForKey:(NSString *)key ofQuery:(NSString*)query{
	NSArray *pairs = [query componentsSeparatedByString:@"&"];
	for(NSString *aPair in pairs){
		NSArray *keyAndValue = [aPair componentsSeparatedByString:@"="];
		if([keyAndValue count] != 2) continue;
		if([[keyAndValue objectAtIndex:0] isEqualToString:key]){
			return [keyAndValue objectAtIndex:1];
		}
	}
	return nil;
}

- (void)dealloc {
	[super dealloc];
	[_data release];
    [verifyWebView release];
	
	[conToken release];
	[conAccessToken release];
	[OAuthInfo release];
	
	[accessUrl release];
	[tokenUrl release];
	[verifyUrl release];
	[cacheName release];
	[appKey release];
	[appSecret release];
}


#pragma mark -
#pragma mark get token && access_token

//Get catch path
- (NSString *)getCatchPath{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	return [NSString stringWithFormat:@"%@/%@", documentsDirectory, cacheName];
}

//Write OAuth info to document folder
- (void)WriteOAuthInfo{
	NSString *path = [self getCatchPath];
	
	[OAuthInfo writeToFile:path atomically:YES];
}

//Parse TokenKey with weibo api Response
- (void)parseTokenKeyWithResponse:(NSString *)Response {
	NSDictionary *params = [NSURL parseURLQueryString:Response];
	[OAuthInfo addEntriesFromDictionary:params];
	
	[self WriteOAuthInfo];
}

//Get tonkenKey
- (void)getTonkenKey{
	QOauthKey *oauthKey = [[[QOauthKey alloc] init] autorelease];
	oauthKey.consumerKey = appKey;
	oauthKey.consumerSecret = appSecret;
	oauthKey.tokenKey = [OAuthInfo objectForKey:TOKEN_KEY];
	oauthKey.tokenSecret = [OAuthInfo objectForKey:TOKEN_SECRET];
	oauthKey.callbackUrl = @"oauth_callback=null";	
	
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
	self.conToken = [request asyncRequestWithUrl:tokenUrl 
									  httpMethod:@"GET"
										oauthKey:oauthKey 
									  parameters:nil 
										   files:nil 
										delegate:self];
	showNetworkActivityIndicator();
	[request release];
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
	NSString *query = [[request URL] query];
	NSString *verifier = [self valueForKey:@"oauth_verifier" ofQuery:query];
	
	if (verifier && ![verifier isEqualToString:@""]) {
		QOauthKey *oauthKey = [[[QOauthKey alloc] init] autorelease];
		oauthKey.consumerKey = appKey;
		oauthKey.consumerSecret = appSecret;
		oauthKey.tokenKey = [OAuthInfo objectForKey:TOKEN_KEY];
		oauthKey.tokenSecret = [OAuthInfo objectForKey:TOKEN_SECRET];
		oauthKey.verify = verifier;
		
		QWeiboRequest *request = [[QWeiboRequest alloc] init];
		self.conAccessToken = [request asyncRequestWithUrl:accessUrl
												httpMethod:@"GET"
												  oauthKey:oauthKey
												parameters:nil
													 files:nil
												  delegate:self];
		
		hideNetworkActivityIndicator();
		[request release];
		
		return NO;
	}
	
	return YES;
}

- (void) webViewDidStartLoad:(UIWebView *)webView{
	showNetworkActivityIndicator();
}

- (void) webViewDidFinishLoad:(UIWebView *)webView{
	hideNetworkActivityIndicator();
}

#pragma mark -
#pragma mark NSURLConnection delegate

/** Reset the received data **/
- (void)resetData {	
	[_data setLength:0];
}

/** Delegate: Call when Receive a new Response, Maybe called serveral times **/
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response{
	[self resetData];
	
    /** Get response code **/
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    int statusCode = [resp statusCode];
	
	NSLog(@"DEHttpConn:didReceiveResponse => HttpCode: %d.", statusCode);
	
    if (statusCode >= 400) {
		//TODO: ERROR
		hideNetworkActivityIndicator();
        [conn cancel];
    } else if (statusCode == 304) {
		/** Destroy the connection. **/
		hideNetworkActivityIndicator();
        [conn cancel];
    }
}

/** Delegate: Append data to _data buffer **/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_data appendData:data];
}

/** Delegate: Call when error happens **/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	//TODO: ERROR
	hideNetworkActivityIndicator();
}

/** Delegate: Call when finish loading **/
- (void)connectionDidFinishLoading:(NSURLConnection *)conn{
	NSString *result = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
	
	NSLog(@"result:%@", result);
	[self parseTokenKeyWithResponse:result];
	
	if (conToken == conn) {
		[self loadWeb];
	} else if (conAccessToken == conn) {
		if ([delegate respondsToSelector:@selector(LogInSucceeded:)]) {
			[delegate LogInSucceeded:OAuthInfo];
		}
		
		[self dismissModalViewControllerAnimated:YES];
	}
	
	hideNetworkActivityIndicator();
	[result release];
}

@end
